import * as cc from "cc";
import { AdConfig } from "../GameSpecial/AdConfig";
import GameConfig from "../GameSpecial/GameConfig";
import { EventType } from "../GameSpecial/GameEventType";
import { GlobalEnum } from "../GameSpecial/GlobalEnum";
import { UserInfo } from "../GameSpecial/PlayerDataTemplate";
import GamePlatform from "../Platform/GamePlatform";
import { GamePlatformType } from "../Platform/GamePlatformType";
import EventManager from "./EventManager";
import GlobalData from "./GlobalData";
import http_request from "./http_request";
import PlayerData from "./PlayerData";

/**
 * 游戏节点、导流节点管理器
 * 游戏节点：加载界面，首页，关卡中，结算页等游戏相关流程
 * 导流节点：导流页，误触页，插屏广告等页面
 */
export default class GameFlow {

    protected constructor() { }

    public static init() {
        this.initFirstFlow();
        this.initRecommendUIConfig();
        this.initStorageConfig();
        this.initDirectFlow();
        this.onEvents();

        this.loadConfig();
    }

    protected static onEvents() {
        EventManager.on(EventType.Common.GameFlow.endFirstFlow, this.endFirstFlow, this);
        EventManager.on(EventType.Common.GameFlow.enterGameFlow, this.onEnterGameFlow, this);
        EventManager.on(EventType.Common.GameFlow.navigateFail, this.onNavigateFail, this);
        EventManager.on(EventType.Common.GameFlow.showInitScene_RecommendDialog, this.showInitScene_RecommendDialog, this);

        EventManager.on(EventType.Common.RecommendEvent.clickRecommendItem, this.onClickRecommendItem, this);
        EventManager.on(EventType.Common.SDKEvent.navigateSuccess, this.onNavigateSuccess, this);
        EventManager.on(EventType.Common.SDKEvent.showBannerFinish, this.onBannerShowSuccess, this);
        EventManager.on(EventType.Common.SDKEvent.showBannerFail, this.onBannerShowFail, this);
        EventManager.on(EventType.Common.SDKEvent.hideBanner, this.onHideBanner, this);

        EventManager.on(EventType.Common.SDKEvent.show, this.onGameShow, this);
        EventManager.on(EventType.Common.SDKEvent.hide, this.onGameHide, this);

    }

    protected static loadConfig() {
        setTimeout(() => {
            EventManager.emit(EventType.Common.GameFlow.loadConfigFinish);
        }, 100);
        console.error("测试阶段，不读取后台配置");
        return;
        let url = http_request.url_ad + "v2.1/api/getGameParam.html";
        let data: any = {
            softid: GamePlatform.Config.appId,
        };
        let api = null;
        if (!!window["wx"]) {
            api = window["wx"];
        } else if (!!window["qq"]) {
            api = window["qq"];
        } else if (!!window["qg"]) {
            api = window["qg"];
            let launch_data = api.getLaunchOptionsSync();
            console.log("OPPO平台启动参数：", launch_data);
            if (!launch_data || !launch_data.referrerInfo) {
                EventManager.once(EventType.Common.SDKEvent.show, this.onGameShow_OPPO, this);
            }
            this.loadConfig_OPPO(launch_data);
            return;
        }

        if (!!api) {
            let launch_data = api.getLaunchOptionsSync();
            if (!!launch_data) {
                let from_appid;
                if (!!launch_data.referrerInfo) {
                    from_appid = launch_data.referrerInfo.appId;
                }
                if (!from_appid) {
                    from_appid = "";
                }
                let query = !!launch_data.query ? JSON.stringify(launch_data.query) : "";
                let scene = launch_data.scene || "";
                let msg = {
                    query: query,
                    scene: scene,
                    from_appid: from_appid,
                    openid: UserInfo.openid
                };
                Object.assign(data, msg);
            }
        } else {
            console.error("测试用，使用虚假路径，避开路径屏蔽");
            data.query = JSON.stringify({ key: "aslkdj" });
            data.scene = 1037;
            data.from_appid = "asd";
            data.openid = "asdhkj";
        }
        http_request.postRequest(url, data, this.saveConfig.bind(this));

    }
    protected static onGameShow_OPPO(launch_data) {
        if (!!launch_data && Object.keys(this.recommendFlowConfig).length == 0) {
            this.loadConfig_OPPO(launch_data);
        }
    }
    protected static loadConfig_OPPO(launch_data) {
        let url = http_request.url_ad + "v2.1/api/getGameParam.html";
        let data: any = {
            softid: GamePlatform.Config.appId,
            query: {},
            scene: "",
            from_appid: "",
            openid: UserInfo.openid,
        };
        if (!!launch_data) {
            let from_appid;
            if (!!launch_data.referrerInfo) {
                from_appid = launch_data.referrerInfo.package;
            }
            if (!from_appid) {
                from_appid = "";
            }
            let query = !!launch_data.query ? JSON.stringify(launch_data.query) : "";
            let scene = launch_data.scene || "";
            let msg = {
                query: query,
                scene: scene,
                from_appid: from_appid,
                openid: UserInfo.openid
            };
            Object.assign(data, msg);
        }
        console.log("拉取开关配置的请求数据：", data);
        http_request.postRequest(url, data, this.saveConfig.bind(this));
    }

    protected static saveConfig(data) {
        console.log("拉取到的开关配置：", data);
        EventManager.emit(EventType.Common.GameFlow.loadConfigFinish);
        let result = data.result;
        if (!result) return;
        this.recommendFlowConfig = result;

        //字符串转换为数字
        for (let step in this.recommendFlowConfig) {
            for (let type in this.recommendFlowConfig[step]) {
                let cfg = this.recommendFlowConfig[step][type];
                for (let key in cfg) {
                    let v = cfg[key];
                    if (typeof v === "string" && v.indexOf("-") < 0 && v.indexOf(",") < 0) {
                        if (v.indexOf(".") >= 0) {
                            v = parseFloat(v);
                        } else {
                            v = parseInt(v);
                        }
                        if (!Number.isNaN(v)) {
                            cfg[key] = v;
                        }
                    }
                }
            }
        }

        //全局开关
        let globalConfig = result.global.default;
        this.globalConfig = globalConfig;
        let guoshen = this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen];
        if (undefined !== guoshen) {
            if (typeof guoshen === "string") {
                this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen] = parseInt(guoshen);
            }
        }
        //广点通过审开关打开时，隐藏所有可能进入全导页的按钮，通过GameConfig记录该配置
        GameConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen] = this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen];
        //广点通过审开关打开时，关闭所有全导页
        if (this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen]) {
            for (let step in this.recommendFlowConfig) {
                if (undefined !== this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.bigPage]) {
                    this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.bigPage][GlobalEnum.Common.RecommendFlowConfig.visible] = 0;
                }
                if (undefined !== this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.middlePage]) {
                    this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.middlePage][GlobalEnum.Common.RecommendFlowConfig.visible] = 0;
                }
                if (undefined !== this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.littlePage]) {
                    this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.littlePage][GlobalEnum.Common.RecommendFlowConfig.visible] = 0;
                }
                if (undefined !== this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.touchBannerUI]) {
                    this.recommendFlowConfig[step][GlobalEnum.Common.RecommendFlowStep.touchBannerUI][GlobalEnum.Common.RecommendFlowConfig.visible] = 0;
                }
            }
        }

        //场景是否被屏蔽
        let enterSceneId;
        if (!!window["wx"]) {
            enterSceneId = window["wx"].getLaunchOptionsSync().scene;
            if (typeof enterSceneId === "number") {
                enterSceneId = enterSceneId.toString();
            }
            console.log("进入场景：", enterSceneId);
        }
        //跳转失败时是否显示小全导
        let v = globalConfig.jumpkaiguan;
        if (typeof v === "string") {
            v = parseInt(v);
        }
        this.navigateFailToLittlePage = !!v && !this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen];

        //banner显示失败或关闭时，是否显示广告位
        v = globalConfig.daoliukaiguan;
        if (typeof v === "string") {
            v = parseInt(v);
        }
        this.recommendInsteadBanner = !!v;

        //导出模式代码转换：将 游戏节点误触配置中的导出模式的代码 转换为与 导流节点误触配置中的导出模式的代码 意义一致
        for (let step in this.recommendFlowConfig) {
            if (undefined !== this.recommendFlowConfig[step].weiyi) {
                let mode = this.recommendFlowConfig[step].weiyi[GlobalEnum.Common.RecommendFlowConfig.mode];
                if (typeof mode === "string") {
                    mode = parseInt(mode);
                }
                if (mode == GlobalEnum.Common.BannerTouchMode.recommend) {
                    this.recommendFlowConfig[step].weiyi[GlobalEnum.Common.RecommendFlowConfig.mode] = GlobalEnum.Common.BannerTouchMode.banner;
                } else if (mode == GlobalEnum.Common.BannerTouchMode.banner) {
                    this.recommendFlowConfig[step].weiyi[GlobalEnum.Common.RecommendFlowConfig.mode] = GlobalEnum.Common.BannerTouchMode.moveButton;
                }
            }
        }

        //首次进入游戏时初始化触发次数
        if (Object.keys(this.storageConfig).length <= 1) {
            for (let step in this.recommendFlowConfig) {
                this.storageConfig[step] = {};
                for (let key in this.recommendFlowConfig[step]) {
                    this.storageConfig[step][key] = {
                        count: 0,
                    };
                }
            }
            cc.sys.localStorage.setItem(GameConfig.gameName + "recommendFlowRecord", JSON.stringify(this.storageConfig));
        }

        this.saveRecommendUIConfig(this.recommendFlowConfig);
        this.saveFirstFlow(this.globalConfig);
    }

    //#region 进入游戏第一轮流程中关闭砸蛋和误触
    protected static isFirstFlow: boolean = true;
    protected static initFirstFlow() {
        let v = PlayerData.getData("gameData.isFirstFlow");
        if (undefined === v) {
            this.isFirstFlow = true;
        } else {
            this.isFirstFlow = !!v;
        }
    }
    protected static saveFirstFlow(data) {
        if (data["nowuchukaiguan"] === 0 || data["nowuchukaiguan"] === "0") {
            this.isFirstFlow = false;
        }
    }
    protected static endFirstFlow() {
        this.isFirstFlow = false;
        EventManager.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
            type: "gameData",
            attribute: "gameData.isFirstFlow",
            mode: "=",
            value: 0,
            emit: false,
            save: false,
        });
    }
    //#endregion

    //#region 流程配置
    /**导流节点配置：每个游戏节点切换到下一个游戏节点时需要经历的导流节点内容配置 */
    protected static recommendFlowConfig: any;
    /**当前游戏节点切换流程的导流节点配置 */
    protected static curRecommendFlowConfig;
    /**导流节点执行顺序：切换游戏节点的过程中，导流节点的执行顺序 */
    protected static recommendFlowSequence: string[];
    /**暂时的特殊处理：从关卡页到结算页（成功奖励/成功/失败页）时的导流节点执行顺序 */
    protected static levelToResultRecommendFlowSequence: string[];
    /**当前显示的导流节点在执行队列中的索引 */
    protected static recommendFlowPtr: number;
    /**当前显示的导流节点枚举值 */
    protected static curRecommendStep: string;

    /**当前所处的游戏节点 */
    protected static curGameFlowStep: string;
    /**要切换到的目标游戏节点 */
    protected static targetGameFlowStep: string;
    /**切换到目标游戏节点时传递的数据 */
    protected static targetGameFlowData: any;

    protected static initDirectFlow() {
        this.recommendFlowSequence = [
            GlobalEnum.Common.RecommendFlowStep.video,
            GlobalEnum.Common.RecommendFlowStep.touchBannerUI,
            GlobalEnum.Common.RecommendFlowStep.insertAd,
            GlobalEnum.Common.RecommendFlowStep.bigPage,
            GlobalEnum.Common.RecommendFlowStep.middlePage,
            GlobalEnum.Common.RecommendFlowStep.littlePage,
            GlobalEnum.Common.RecommendFlowStep.dialog,
        ];
        this.levelToResultRecommendFlowSequence = [
            GlobalEnum.Common.RecommendFlowStep.bigPage,
            GlobalEnum.Common.RecommendFlowStep.middlePage,
            GlobalEnum.Common.RecommendFlowStep.littlePage,
            GlobalEnum.Common.RecommendFlowStep.dialog,
            GlobalEnum.Common.RecommendFlowStep.video,
            GlobalEnum.Common.RecommendFlowStep.touchBannerUI,
            GlobalEnum.Common.RecommendFlowStep.insertAd,
        ];
        this.recommendFlowPtr = 0;

        this.recommendFlowConfig = {};

        this.curGameFlowStep = GlobalEnum.Common.GameFlowStep.initScene;
    }

    /**开关配置 */
    public static getConfig(type?) {
        if (undefined !== type) {
            return this.recommendFlowConfig[type];
        } else {
            return this.recommendFlowConfig;
        }
    }
    //#endregion

    //#region 全局配置
    /**全局开关 */
    protected static globalConfig = {};
    /**广告位跳转取消后，是否显示小全导 */
    protected static navigateFailToLittlePage: boolean = false;
    /**是否已进入过首页 */
    protected static enteredLobby: boolean = false;

    /**banner展示失败或点击切换后在相应位置展示广告位 */
    protected static recommendInsteadBanner: boolean = false;

    /**全局配置 */
    public static getGlobalConfig(type?) {
        if (undefined !== type) {
            return this.globalConfig[type];
        } else {
            return this.globalConfig;
        }
    }
    /**设置全局配置，会覆盖原有配置 */
    public static setGlobalConfig(type, value) {
        this.globalConfig[type] = value;
    }
    //#endregion

    //#region 本地配置记录
    /**本地配置记录 */
    protected static storageConfig: any;
    protected static initStorageConfig() {
        let day = new Date().getDate();
        let data = cc.sys.localStorage.getItem(GameConfig.gameName + "recommendFlowRecord");
        if (!!data) {
            this.storageConfig = JSON.parse(data);
        } else {
            this.storageConfig = {};
        }
        if (this.storageConfig.saveDay != day) {
            this.storageConfig = {
                saveDay: day,
            };
        }

    }
    protected static getStorageConfigCount(step, config) {
        if (!this.storageConfig) return null;
        if (!this.storageConfig[step]) return null;
        if (!this.storageConfig[step][config]) return null;
        return this.storageConfig[step][config].count;
    }
    protected static updateStorageConfigCount(step, config, value) {
        if (!this.storageConfig) return;
        if (!this.storageConfig[step]) {
            this.storageConfig[step] = {};
        }
        if (!this.storageConfig[step][config]) {
            this.storageConfig[step][config] = {};
        }
        this.storageConfig[step][config].count = value;
        cc.sys.localStorage.setItem(GameConfig.gameName + "recommendFlowRecord", JSON.stringify(this.storageConfig));
    }
    //#endregion

    //#region 导流页配置
    /**各全导页的配置,key:全导页的广告位id,value:具体配置 */
    protected static recommendUIConfig: { [locationid: string]: any };
    protected static initRecommendUIConfig() {
        this.recommendUIConfig = {};
    }
    protected static saveRecommendUIConfig(data) {
        this.recommendUIConfig = {};
        for (let key in data) {
            if (!!data[key]["daquandao"] && data[key]["daquandao"]["kaiguan"] == 1) {
                this.recommendUIConfig[AdConfig.AdID.bigView] = data[key]["daquandao"];
            }
            if (!!data[key]["zhongquandao"] && data[key]["zhongquandao"]["kaiguan"] == 1) {
                this.recommendUIConfig[AdConfig.AdID.middleView] = data[key]["zhongquandao"];
            }
            if (!!data[key]["xiaoquandao"] && data[key]["xiaoquandao"]["kaiguan"] == 1) {
                this.recommendUIConfig[AdConfig.AdID.littleView] = data[key]["xiaoquandao"];
            }
            if (!!data[key]["alert"] && data[key]["alert"]["kaiguan"] == 1) {
                this.recommendUIConfig[AdConfig.AdID.dialog] = data[key]["alert"];
            }
        }
    }
    public static getRecommendUIConfig(locationid: string) {
        return this.recommendUIConfig[locationid];
    }
    //#endregion

    //#region 游戏流程
    /**切换到指定的游戏节点 */
    protected static onEnterGameFlow(step, data) {
        this.recommendFlowPtr = -1;
        this.targetGameFlowStep = step;
        this.targetGameFlowData = data;
        this.curRecommendFlowConfig = this.getCurRecommendFlowConfig();

        if (!!this.curRecommendFlowConfig) {
            this.onNextRecommendFlow();
        } else {
            this.enterGameFlow(step);
        }
    }
    protected static getCurRecommendFlowConfig() {
        let str = this.getCurRecommendFlowName();
        let key = configMap[str];
        return this.recommendFlowConfig[key];
    }
    /**当前游戏节点切换流程对应的导流配置名称 */
    protected static getCurRecommendFlowName() {
        if (null === this.targetGameFlowStep) {
            return null;
        }
        return this.curGameFlowStep + "_" + this.targetGameFlowStep;
    }
    /**进入游戏节点 */
    protected static enterGameFlow(step) {
        this.curRecommendStep = null;
        let cfg = this.getBtnMoveForBannerConfig(step);
        if (!!cfg) {
            cfg = this.getFirstCfg(cfg, this.isFirstFlow);
        }
        this.curGameFlowStep = step;
        this.targetGameFlowStep = null;
        let data = this.targetGameFlowData;
        this.targetGameFlowData = null;
        //阿拉丁统计
        if (step !== GlobalEnum.Common.GameFlowStep.recommendDialog) {
            EventManager.emit(EventType.Common.ALDEvent.enterGameFlow, step);
        }
        switch (step) {
            case GlobalEnum.Common.GameFlowStep.initScene: {
                break;
            }
            case GlobalEnum.Common.GameFlowStep.recommendDialog: {
                EventManager.emit(EventType.Common.GameFlow.enterGameFlow, GlobalEnum.Common.GameFlowStep.lobby);
                // if (this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.guoshen]) {
                //     EventManager.emit(EventType.Common.GameFlow.enterGameFlow, GlobalEnum.Common.GameFlowStep.lobby);
                // } else {
                //     EventManager.emit(EventType.Common.RecommendEvent.showRecommendDialog, { data: data, config: cfg });
                // }
                break;
            }
            case GlobalEnum.Common.GameFlowStep.lobby: {
                EventManager.emit(EventType.Common.DirectorEvent.enterLobby, data);
                this.enteredLobby = true;
                break;
            }
            case GlobalEnum.Common.GameFlowStep.level: {
                EventManager.emit(EventType.Common.GameFlow.enterLevel, data);
                break;
            }
            case GlobalEnum.Common.GameFlowStep.award: {
                EventManager.emit(EventType.Common.UIEvent.enter, GlobalEnum.UI.awardUI, { data: data, config: cfg });
                break;
            }
            case GlobalEnum.Common.GameFlowStep.win: {
                EventManager.emit(EventType.Common.UIEvent.enter, GlobalEnum.UI.winUI, { data: data, config: cfg });
                if (GamePlatform.Config.type == GamePlatformType.OPPO) {
                    let showNative = GameFlow.getGlobalConfig(GlobalEnum.Common.GameFlowGlobalConfig.showNativeAdUI);
                    console.log("显示原生广告页UI:", showNative);
                    if (!!showNative) {
                        let c = GameFlow.getGlobalConfig(GlobalEnum.Common.GameFlowGlobalConfig.showNativeAdUICount);
                        console.log("原生广告页显示剩余次数：", c);
                        if (typeof c === "string") {
                            c = parseInt(c);
                        }
                        if (c > 0) {
                            GameFlow.setGlobalConfig(GlobalEnum.Common.GameFlowGlobalConfig.showNativeAdUICount, c - 1);
                            EventManager.emit(EventType.Common.UIEvent.enter, GlobalEnum.UI.winNativeAdUI);
                        }
                    }
                }
                break;
            }
            case GlobalEnum.Common.GameFlowStep.lose: {
                EventManager.emit(EventType.Common.UIEvent.enter, GlobalEnum.UI.loseUI, { data: data, config: cfg });
                if (GamePlatform.Config.type == GamePlatformType.OPPO) {
                    let showNative = GameFlow.getGlobalConfig(GlobalEnum.Common.GameFlowGlobalConfig.showNativeAdUI);
                    console.log("显示原生广告页UI:", showNative);
                    if (!!showNative) {
                        let c = GameFlow.getGlobalConfig(GlobalEnum.Common.GameFlowGlobalConfig.showNativeAdUICount);
                        console.log("原生广告页显示剩余次数：", c);
                        if (typeof c === "string") {
                            c = parseInt(c);
                        }
                        if (c > 0) {
                            GameFlow.setGlobalConfig(GlobalEnum.Common.GameFlowGlobalConfig.showNativeAdUICount, c - 1);
                            EventManager.emit(EventType.Common.UIEvent.enter, GlobalEnum.UI.loseNativeAdUI);
                        }
                    }
                }
                break;
            }
            default:
                break;
        }

    }
    protected static getBtnMoveForBannerConfig(step) {
        let str;
        switch (step) {
            case GlobalEnum.Common.GameFlowStep.recommendDialog: {
                str = GlobalEnum.Common.GameFlowStep.recommendDialog + "_" + GlobalEnum.Common.GameFlowStep.lobby;
                break;
            }
            case GlobalEnum.Common.GameFlowStep.award:
            case GlobalEnum.Common.GameFlowStep.win:
            case GlobalEnum.Common.GameFlowStep.lose: {
                str = step + "_" + GlobalEnum.Common.GameFlowStep.recommendDialog;
                break;
            }
        }
        let key = configMap[str];
        if (!!key) {
            if (!!this.recommendFlowConfig[key]) {
                return this.recommendFlowConfig[key].weiyi;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
    //#endregion

    //#region 导流节点
    /**执行下一个导流节点 */
    protected static onNextRecommendFlow() {
        let seq = this.recommendFlowSequence;
        let str = this.getCurRecommendFlowName();
        let key = configMap[str];
        if (key == configMap.Level_AwardUI
            || key == configMap.Level_WinUI
            || key == configMap.Level_LoseUI
        ) {
            seq = this.levelToResultRecommendFlowSequence;
        }
        let flowName = this.getCurRecommendFlowName();
        while (++this.recommendFlowPtr < seq.length) {
            //加载页到首页过程中的中全导，在首页显示之后再由首页发送事件显示
            if (this.curGameFlowStep == GlobalEnum.Common.GameFlowStep.initScene
                || this.curGameFlowStep == GlobalEnum.Common.GameFlowStep.recommendDialog) {
                if (this.targetGameFlowStep == GlobalEnum.Common.GameFlowStep.lobby
                    || this.targetGameFlowStep == GlobalEnum.Common.GameFlowStep.recommendDialog) {
                    if (seq[this.recommendFlowPtr] == GlobalEnum.Common.RecommendFlowStep.dialog) {
                        // console.log("不显示弹窗");
                        this.recommendFlowPtr++;
                        continue;
                    }
                }
            }
            let cfg = this.curRecommendFlowConfig[seq[this.recommendFlowPtr]];
            if (undefined === cfg || cfg[GlobalEnum.Common.RecommendFlowConfig.visible] == 0) {
                continue;
            }
            if (undefined !== cfg[GlobalEnum.Common.RecommendFlowConfig.count]) {
                let c = this.getStorageConfigCount(flowName, seq[this.recommendFlowPtr]);
                if (null === c) {
                    c = 0;
                }
                if (cfg[GlobalEnum.Common.RecommendFlowConfig.count] <= c) {
                    continue;
                }
                this.updateStorageConfigCount(flowName, seq[this.recommendFlowPtr], c + 1);
            }
            this.enterRecommendFlow(seq[this.recommendFlowPtr], cfg);
            return;
        }
        this.recommendFlowPtr = -1;
        this.enterGameFlow(this.targetGameFlowStep);
    }
    /**进入导流节点 */
    protected static enterRecommendFlow(step, cfg) {
        this.curRecommendStep = step;
        let gameStep = this.curGameFlowStep;
        EventManager.emit(EventType.Common.ALDEvent.enterRecommendFlow, gameStep, step);
        if (step !== GlobalEnum.Common.RecommendFlowStep.middlePage) {
            cfg = this.getFirstCfg(cfg, this.isFirstFlow);
        }
        switch (step) {
            //游戏弹窗
            case GlobalEnum.Common.RecommendFlowStep.dialog: {
                EventManager.once(EventType.Common.RecommendEvent.closeRecommendDialog, this.onNextRecommendFlow, this);
                EventManager.emit(EventType.Common.RecommendEvent.showRecommendDialog, { config: cfg });
                break;
            }
            //视频
            case GlobalEnum.Common.RecommendFlowStep.video: {
                if (this.isFirstFlow) {
                    setTimeout(() => {
                        this.onNextRecommendFlow();
                    }, 0);
                } else {
                    EventManager.emit(EventType.Common.SDKEvent.showVideo, {
                        success: this.onVideoSuccess.bind(this),
                        fail: this.onVideoFail.bind(this),
                        quit: this.onVideoQuit.bind(this),
                    });
                }
                break;
            }
            //砸蛋
            case GlobalEnum.Common.RecommendFlowStep.touchBannerUI: {
                if (this.isFirstFlow) {
                    setTimeout(() => {
                        this.onNextRecommendFlow();
                    }, 0);
                } else {
                    cfg[GlobalEnum.Common.GameFlowGlobalConfig.mustTouchBanner] = this.globalConfig[GlobalEnum.Common.GameFlowGlobalConfig.mustTouchBanner];
                    let ui = this.getTouchBannerUI(cfg);
                    //有banner则进入砸蛋页，没有则跳过砸蛋，继续下一步
                    EventManager.emit(EventType.Common.SDKEvent.checkVisibleBanner, {
                        cb: (config) => {
                            EventManager.once(EventType.Common.UIEvent.touchBannerFinish, this.onNextRecommendFlow, this);
                            EventManager.emit(EventType.Common.UIEvent.enter, ui, { config: config });
                        },
                        target: this,
                        data: cfg,
                    }, {
                        cb: this.onNextRecommendFlow.bind(this),
                    });
                }
                break;
            }
            //插屏
            case GlobalEnum.Common.RecommendFlowStep.insertAd: {
                if (!this.isFirstFlow) {
                    EventManager.emit(EventType.Common.SDKEvent.showInsertAd);
                }
                setTimeout(() => {
                    this.onNextRecommendFlow();
                }, 0);
                break;
            }
            //大全导
            case GlobalEnum.Common.RecommendFlowStep.bigPage: {
                EventManager.once(EventType.Common.RecommendEvent.closeBigPage, this.onNextRecommendFlow, this);
                EventManager.emit(EventType.Common.RecommendEvent.showBigPage, { config: cfg });
                break;
            }
            //中全导
            case GlobalEnum.Common.RecommendFlowStep.middlePage: {
                EventManager.once(EventType.Common.RecommendEvent.closeMiddlePage, this.onNextRecommendFlow, this);
                EventManager.emit(EventType.Common.RecommendEvent.showMiddlePage, { config: cfg });
                break;
            }
            //小全导
            case GlobalEnum.Common.RecommendFlowStep.littlePage: {
                EventManager.once(EventType.Common.RecommendEvent.closeLittlePage, this.onNextRecommendFlow, this);
                EventManager.emit(EventType.Common.RecommendEvent.showLittlePage, { config: cfg });
                break;
            }
            default: {
                console.error("游戏导流节点未做处理：", step);
                break;
            }
        }
    }
    protected static getFirstCfg(cfg, first = false) {
        if (!first) {
            return cfg;
        }
        let data = {};
        Object.assign(data, cfg);
        data[GlobalEnum.Common.RecommendFlowConfig.mode] = 1;
        data[GlobalEnum.Common.RecommendFlowConfig.resultBannerShowDelay] = 0;
        return data;
    }
    /**当前流程需要显示的砸蛋页名称 */
    protected static getTouchBannerUI(cfg) {
        //随机选择砸蛋页面
        let mode = cfg["zadanstyle"];
        if (undefined === mode) {
            mode = "123";
        } else if (typeof mode === "number") {
            mode = mode.toString();
        }
        if (mode === "z" || mode === "0") {
            mode = "123";
        }
        let index = Math.floor(Math.random() * (mode.length - 0.0001));
        return "TouchBannerUI" + mode[index];
    }
    protected static onVideoSuccess() {
        this.onNextRecommendFlow();
    }
    protected static onVideoFail() {
        this.onNextRecommendFlow();
    }
    protected static onVideoQuit() {
        this.onNextRecommendFlow();
    }
    /**特殊流程：加载页到首页的中全导，在首页显示之后再显示 */
    protected static showInitScene_RecommendDialog() {
        let indexalertkaiguan = GameFlow.getGlobalConfig("indexalertkaiguan");
        if (!indexalertkaiguan) return;
        if (!this.recommendFlowConfig || !this.recommendFlowConfig[configMap.InitScene_RecommendDialog]) return;
        let cfg = this.recommendFlowConfig[configMap.InitScene_RecommendDialog][GlobalEnum.Common.RecommendFlowStep.dialog];
        EventManager.emit(EventType.Common.RecommendEvent.showRecommendDialog, {
            config: cfg,
        });
    }
    //#endregion

    /********************************************事件回调********************************************/
    //#region 广告位跳转事件
    protected static isNavigating: boolean = false;
    protected static onClickRecommendItem() {
        EventManager.emit(EventType.Common.ALDEvent.clickGame, this.curGameFlowStep, this.curRecommendStep);
    }
    /**广告位跳转失败，显示小全导 */
    protected static onNavigateFail(data) {
        this.isNavigating = false;
        if (!this.navigateFailToLittlePage || !this.enteredLobby) return;
        //大全导页广告位取消跳转时不显示小全导
        if (data && data.locationid == AdConfig.AdID.bigView) return;
        //中全导页广告位取消跳转时不显示小全导
        if (data && data.locationid == AdConfig.AdID.middleView) return;
        //小全导页广告位取消跳转时不显示小全导
        if (data && data.locationid == AdConfig.AdID.littleView) return;

        EventManager.emit(EventType.Common.RecommendEvent.showLittlePage);
    }
    protected static onNavigateSuccess() {
        this.isNavigating = true;
    }
    //#endregion

    //#region banner事件
    /**banner显示成功，注册事件：切出再切回游戏时，隐藏banner，显示广告位 */
    protected static bannerActive: boolean = false;
    protected static onBannerShowSuccess() {
        this.bannerActive = true;
    }
    protected static onBannerShowFail(style) {
        this.bannerActive = false;
        //微信平台开启功能：banner显示失败时用广告位代替
        // if (!!window["wx"]) {
        this.showRecommendInsteadBanner(style);
        // }
        EventManager.emit(EventType.Common.SDKEvent.showBannerSuccess);
    }
    /**banner显示失败时，显示广告位 */
    protected static showRecommendInsteadBanner(style?) {
        console.log("GameFlow.showRecommendInsteadBanner.hideBanner");
        EventManager.emit(EventType.Common.SDKEvent.hideBanner);
        let w = 750;
        let cvs = GlobalData.get(GlobalEnum.Common.GlobalDataType.canvasTransform);
        //横屏游戏处理
        if (cvs.width > cvs.height) {
            w = 600;
            let wdg: any = {};
            if (!!style) {
                switch (style.horizontal) {
                    case "left": {
                        wdg.left = 20;
                        break;
                    }
                    case "middle": {
                        wdg.horizontalCenter = true;
                        break;
                    }
                    case "right": {
                        wdg.right = 20;
                        break;
                    }
                    default: {
                        wdg.horizontalCenter = true;
                        break;
                    }
                }
                if (undefined !== style.top) {
                    wdg.top = style.top;
                } else if (undefined !== style.bottom) {
                    wdg.bottom = style.bottom;
                } else {
                    wdg.bottom = 20;
                }
            } else {
                wdg.horizontalCenter = true;
                wdg.bottom = 20;
            }
            wdg.width = 600;
            wdg.height = 170;
            EventManager.emit(EventType.Common.RecommendEvent.showInsteadBannerRecommend, {
                "name": "RecommendBanner_H",
                "AdID": "friend",
                "itemType": "icon",
                "widget": wdg,
            });
        } else {
            EventManager.emit(EventType.Common.RecommendEvent.showInsteadBannerRecommend, {
                "name": "RecommendBanner_H",
                "AdID": "friend",
                "itemType": "icon",
                "widget": {
                    "left": 0,
                    "right": 0,
                    "bottom": 20,
                    "height": 170
                }
            });
        }
    }
    protected static onHideBanner() {
        this.bannerActive = false;
    }
    //#endregion

    //#region 游戏前后台切换事件
    /**回到小游戏 */
    protected static onGameShow() {
        if (this.isNavigating) {
            EventManager.emit(EventType.Common.ALDEvent.jumpGame, this.curGameFlowStep, this.curRecommendStep);
            this.isNavigating = false;
        } else if (this.bannerActive) {
            EventManager.emit(EventType.Common.ALDEvent.touchBanner, this.curGameFlowStep, this.curRecommendStep);
        }
    }
    protected static onGameHide() { }
    //#endregion

}

const configMap = {
    InitScene_RecommendDialog: "loading",
    RecommendDialog_GameLobby: "alert",
    GameLobby_Level: "index",
    Level_AwardUI: "game",
    Level_WinUI: "game",
    Level_LoseUI: "game",
    AwardUI_RecommendDialog: "success",
    WinUI_RecommendDialog: "success",
    LoseUI_RecommendDialog: "fail",
    //结算页点击下一关/继续游戏后，直接进入关卡：
    WinUI_Level: "nextlevel",
    LoseUI_Level: "nextlevel",
}
